package com.gzhryc.shared_device.cdcz.code.services;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.cdcz.code.dao.CDCZFeeTemplateDao;
import com.gzhryc.shared_device.cdcz.code.CDCZCostConfig;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZFeeTemplate;
import com.gzhryc.shared_device.cdcz.code.dao.models.CDCZPowerIntervalMoneyContent;
import com.gzhryc.shared_device.cdcz.code.services.dto.CDCZFeeTemplateSearch;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CDCZFeeTemplateService {

    static Logger log = Logger.getLogger(CDCZFeeTemplateService.class);

    public static CDCZFeeTemplateService self() {
        return MultiDBTools.getService(CDCZFeeTemplateService.class, true);
    }

    public static CDCZFeeTemplateService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, CDCZFeeTemplateService.class, true);
    }

    CDCZFeeTemplateDao dao;

    public CDCZFeeTemplateService(String jdbcKey) {
        dao = new CDCZFeeTemplateDao(jdbcKey);
    }

    public List<CDCZFeeTemplate> findJoinBySearch(CDCZFeeTemplateSearch search,Integer pageNo,Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        try {
            return dao.findJoinByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countJoinBySearch(CDCZFeeTemplateSearch search){
        Conditions conditions = dao.buildConditions(search);
        try {
            return dao.countJoin(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public List<CDCZFeeTemplate> findByUserId(Long userId){
        if(userId != null){
            Conditions conditions = new Conditions(CDCZFeeTemplate.class);
            conditions.and().is("userId",userId);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public CDCZFeeTemplate getById(Long id) {
        if(id != null) {
            try {
                return dao.getById(id);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public CDCZFeeTemplate getJoinById(Long id) {
        if(id != null) {
            try {
                return dao.getJoinById(id);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public boolean add(CDCZFeeTemplate feeTemplate)throws LogicException {
        if(feeTemplate.getUserId() == null){
            feeTemplate.setUserId(0L);  //不设置则是平台模版
        }
        feeTemplate.setCreateDate(new Date());
        try {
            return dao.insert(feeTemplate) > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean updateNotNull(CDCZFeeTemplate feeTemplate) throws LogicException {
        try {
            return dao.updateNotNull(feeTemplate) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    public boolean addPowerIntervalMoneyItem(CDCZFeeTemplate feeTemplate, CDCZPowerIntervalMoneyContent.Item theItem)  throws LogicException{
        if(feeTemplate == null){
            throw new LogicException("未找到网点的费用配置");
        }
        CDCZPowerIntervalMoneyContent content = null;
        if(StringTools.isNotBlank(feeTemplate.getPimContent())) {
            content = JsonTools.fromJson(feeTemplate.getPimContent(), CDCZPowerIntervalMoneyContent.class);
        }else{
            content = new CDCZPowerIntervalMoneyContent();
        }
        if(content.getItems().size() > 0) {
            CDCZPowerIntervalMoneyContent.Item downItem = null;
            for (int i = 0; i < content.getItems().size(); i++) {
                CDCZPowerIntervalMoneyContent.Item item = content.getItems().get(i);
                if (item.getMaxPower().equals(theItem.getMinPower())) {
                    downItem = item;
                    break;
                }
            }
            if (downItem == null) {
                throw new LogicException("未找到关联网点的功率区间费用配置");
            }
        }

        content.getItems().add(theItem);

        CDCZFeeTemplate updateEntity = new CDCZFeeTemplate();
        updateEntity.setId(feeTemplate.getId());
        updateEntity.setPimContent(JsonTools.toJson(content));
        try {
            return dao.updateNotNull(updateEntity) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean updatePowerIntervalMoneyItem(CDCZFeeTemplate feeTemplate, CDCZPowerIntervalMoneyContent.Item theItem)  throws LogicException{
        if(feeTemplate == null || StringTools.isBlank(feeTemplate.getPimContent())){
            throw new LogicException("未找到网点的功率区间费用配置");
        }
        CDCZPowerIntervalMoneyContent powerIntervalMoneyContent = JsonTools.fromJson(feeTemplate.getPimContent(),CDCZPowerIntervalMoneyContent.class);
        CDCZPowerIntervalMoneyContent.Item upItem = null;
        List<CDCZPowerIntervalMoneyContent.Item> items = new ArrayList<>();
        for(int i =0 ;i<powerIntervalMoneyContent.getItems().size();i++){
            CDCZPowerIntervalMoneyContent.Item item = powerIntervalMoneyContent.getItems().get(i);
            if(item.getMinPower().equals(theItem.getMinPower())) {
                if(!item.getMaxPower().equals(theItem.getMaxPower())) { //修改了最大功率
                    if ((i + 1) < powerIntervalMoneyContent.getItems().size()) {
                        upItem = powerIntervalMoneyContent.getItems().get((i + 1));
                        if (upItem.getMaxPower() < theItem.getMaxPower()) {
                            throw new LogicException("最大功率超过功率区间链");
                        } else {
                            upItem.setMinPower(theItem.getMaxPower());
                        }
                        i = i + 1;
                    }
                }
                item = theItem;
            }

            items.add(item);
            if(upItem != null){
                items.add(upItem);
                upItem = null;
            }
        }

        powerIntervalMoneyContent.setItems(items);

        CDCZFeeTemplate updateEntity = new CDCZFeeTemplate();
        updateEntity.setId(feeTemplate.getId());
        updateEntity.setPimContent(JsonTools.toJson(powerIntervalMoneyContent));

        try {
            return dao.updateNotNull(updateEntity) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean deletePowerIntervalMoneyItem(CDCZFeeTemplate feeTemplate, Double minPower) throws LogicException{
        if(feeTemplate == null || StringTools.isBlank(feeTemplate.getPimContent())){
            throw new LogicException("未找到网点的功率区间费用配置");
        }
        CDCZPowerIntervalMoneyContent powerIntervalMoneyContent = JsonTools.fromJson(feeTemplate.getPimContent(),CDCZPowerIntervalMoneyContent.class);
        CDCZPowerIntervalMoneyContent.Item theItem = null;
        CDCZPowerIntervalMoneyContent.Item upItem = null;
        CDCZPowerIntervalMoneyContent.Item downItem = null;
        List<CDCZPowerIntervalMoneyContent.Item> items = new ArrayList<>();
        for(int i =0 ;i<powerIntervalMoneyContent.getItems().size();i++){
            CDCZPowerIntervalMoneyContent.Item item = powerIntervalMoneyContent.getItems().get(i);
            if(item.getMinPower().equals(minPower)) {
                theItem = item;
                if ((i + 1) < powerIntervalMoneyContent.getItems().size()) {
                    upItem = powerIntervalMoneyContent.getItems().get((i + 1));
                }else if((i - 1) >= 0){
                    downItem = powerIntervalMoneyContent.getItems().get((i - 1));
                }
                break;
            }
        }

        if(theItem == null){
            throw new LogicException("不存在该功率区间");
        }

        if(upItem != null || downItem != null) {
            for (int i = 0; i < powerIntervalMoneyContent.getItems().size(); i++) {
                CDCZPowerIntervalMoneyContent.Item item = powerIntervalMoneyContent.getItems().get(i);
                if (!item.getMinPower().equals(minPower)) {
                    if (downItem != null && downItem.getMinPower().equals(item.getMinPower())) {
                        downItem.setMaxPower(minPower);
                        items.add(downItem);
                    } else if (upItem != null && upItem.getMinPower().equals(item.getMinPower())) {
                        upItem.setMinPower(minPower);
                        items.add(upItem);
                    } else {
                        items.add(item);
                    }
                }
            }

            powerIntervalMoneyContent.setItems(items);

            CDCZFeeTemplate updateEntity = new CDCZFeeTemplate();
            updateEntity.setId(feeTemplate.getId());
            updateEntity.setPimContent(JsonTools.toJson(powerIntervalMoneyContent));

            try {
                return dao.updateNotNull(updateEntity) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }else {
            CDCZFeeTemplate updateEntity = new CDCZFeeTemplate();
            updateEntity.setId(feeTemplate.getId());
            updateEntity.setPimContent(null);

            try {
                return dao.updateNotNull(updateEntity,"pimContent") > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean deleteById(Long id) throws LogicException {
        try {
            return dao.deleteById(id) >0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }


    public static CDCZFeeTemplate buildByDefault(CDCZCostConfig config){
        CDCZFeeTemplate feeTemplate = new CDCZFeeTemplate();
        feeTemplate.setTimeSetMeal(config.getTimeSetMeal());
        feeTemplate.setMinWalletMoney(config.getMinWalletMoney());
        feeTemplate.setMaxChargeTimesMinute(config.getMaxTimesMinute());
        feeTemplate.setMaxChargeElectricity(config.getMaxChargeElectricity());
        feeTemplate.setPimContent(config.getPimContent());
        return feeTemplate;
    }
}
